package com.ita.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.ita.dto.VerifyDto;
import com.ita.httpclient.CheckClient;
import com.ita.pojo.MUser;
import com.ita.pojo.TenderRecord;
import com.ita.service.MUserService;
import com.ita.util.Base64Util;
import com.ita.util.Constant;
import com.ita.util.FileUtil;
import com.ita.util.JsonResult;
import com.ita.vo.MUserVo;

@Controller
public class MUserController {

	@Autowired(required = true)
	private MUserService mService;

	@RequestMapping(value = "muser/regist", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult regist(MultipartHttpServletRequest req) throws UnknownHostException {

		String server_path = "http://" + InetAddress.getLocalHost().getHostAddress() + Constant.FILE_PORT;
		JsonResult jr = new JsonResult();

		String addr = req.getParameter("address");
		String name = req.getParameter("name");
		String pwd = req.getParameter("pwd");
		String storeName = req.getParameter("storename");

		if (("".equals(addr)) || ("".equals(name)) || ("".equals(pwd)) || ("".equals(storeName))) {
			jr.setMsg("fields are empty !");
			jr.setCode(Constant.FAIL);
			return jr;
		}

		MUser mUser = new MUser();
		mUser.setId(UUID.randomUUID().toString());
		mUser.setAddress(addr);
		mUser.setName(name);
		mUser.setPwd(pwd);
		mUser.setStore_name(storeName);

		if (mService.getByName(name) != null) {
			jr.setMsg("Name already exist");
			jr.setCode(Constant.FAIL);
			return jr;
		}

		String idcard = Constant.IDCARD;
		String img = Constant.IMG;
		String filePath = "";

		Iterator<String> iter = req.getFileNames();
		try {

			while (iter.hasNext()) {

				MultipartFile file = req.getFile(iter.next());
				if (file != null) {

					String fileName = file.getOriginalFilename();
					String image_type = fileName.subSequence(fileName.lastIndexOf("."), fileName.length()).toString();
					InputStream in;
					String base64 = "";
					byte[] buff = null;
					try {
						in = file.getInputStream();
						buff = new byte[in.available()];
						in.read(buff);
					} catch (IOException e) {
						e.printStackTrace();
					}
					switch (file.getName()) {
					case "idcard":
						filePath = Constant.IDCARD_PATH + mUser.getId() + image_type;
						idcard = idcard + mUser.getId() + image_type;
						base64 = Base64Util.byteToBase64(buff);
						mUser.setIdcard(base64);
						break;
					case "img":
						filePath = Constant.IMG_PATH + mUser.getId() + image_type;
						img = img + mUser.getId() + image_type;
						base64 = Base64Util.byteToBase64(buff);
						mUser.setImg(base64);
						break;
					}

					FileUtil.writeFile(filePath, buff);
				} else {
					jr.setCode(400);
					jr.setMsg("Not select image");
					return jr;
				}
			}
		} catch (Exception e) {
			jr.setCode(Constant.FAIL);
			jr.setMsg("Not select image");
			return jr;
		}
		mUser.setIdcard(server_path + idcard);
		mUser.setImg(server_path + img);
		mService.sendToMQ(mUser);
		mService.regist(mUser);
		jr.setCode(Constant.SUCCESS);
		jr.setData(mUser);
		return jr;
	}

	@RequestMapping(value = "muser/login", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public JsonResult login(@RequestBody MUserVo MUserVo, HttpSession session) throws UnknownHostException {

		JsonResult jr = new JsonResult();
		String name = MUserVo.getName();
		String pwd = MUserVo.getPwd();
		MUser m = mService.login(name, pwd);
		if (m != null) {// right password and name
			if (m.getState() != 1) {
				try {
					CheckClient client = new CheckClient(m.getId());
					VerifyDto vd = client.getInfo();
					m.setState(vd.getState());
					m.setBlock(vd.getBlock());
					m.setMsg(vd.getMsg());
				} catch (IOException e) {
					jr.setCode(Constant.EXCEPTION);
					return jr;
				}
			}
			session.setAttribute(Constant.CURRENT_MERCHANT, m);
			session.setAttribute(Constant.CLIENT_ID, m.getId());
			jr.setCode(Constant.SUCCESS);
			jr.setCode(200);
			jr.setData(m);
		} else {
			jr.setCode(Constant.FAIL);
			jr.setMsg("name not exist or password error");
		}
		return jr;
		// JsonResult jr = new JsonResult();
		// String name = MUserVo.getName();
		// String pwd = MUserVo.getPwd();
		// MUser m = mService.login(name, pwd);
		//
		// if (m != null) {
		// session.setAttribute(Constant.CURRENT_MERCHANT, m);
		// session.setAttribute(Constant.CLIENT_ID, m.getId());
		// jr.setCode(Constant.SUCCESS);
		// jr.setCode(200);
		// jr.setData(m);
		// } else {
		// jr.setCode(Constant.FAIL);
		// jr.setMsg("name not exist or password error");
		// }
		// return jr;

	}

	@RequestMapping(value = "sec/muser/update", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult update(MultipartHttpServletRequest req, HttpSession session) throws UnknownHostException {

		String server_path = "http://" + InetAddress.getLocalHost().getHostAddress() + Constant.FILE_PORT;
		JsonResult jr = new JsonResult();
		MUser mUser = (MUser) session.getAttribute("m");

		String addr = req.getParameter("updateAddr");
		// String name = req.getParameter("updateName");
		String storeName = req.getParameter("updateStoreName");

		if (("".equals(addr)) || ("".equals(storeName))) {
			jr.setMsg("fields are empty !");
			jr.setCode(Constant.FAIL);
			return jr;
		}

		mUser.setAddress(addr);
		mUser.setStore_name(storeName);

		// if (mService.getByName(name) != null) {
		// jr.setMsg("name already exist");
		// jr.setCode(400);
		// return jr;
		// }

		String idcard = Constant.IDCARD;
		String img = Constant.IMG;
		String filePath = "";
		try {

			Iterator<String> iter = req.getFileNames();
			while (iter.hasNext()) {

				MultipartFile file = req.getFile(iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					String image_type = fileName.subSequence(fileName.lastIndexOf("."), fileName.length()).toString();
					InputStream in;
					String base64 = "";
					byte[] buff = null;
					try {
						in = file.getInputStream();
						buff = new byte[in.available()];
						in.read(buff);
					} catch (IOException e) {
						e.printStackTrace();
					}
					switch (file.getName()) {
					case "updateIacard":
						filePath = Constant.IDCARD_PATH + mUser.getId() + image_type;
						idcard = idcard + mUser.getId() + image_type;
						base64 = Base64Util.byteToBase64(buff);
						mUser.setIdcard(base64);
						break;
					case "updateImg":
						filePath = Constant.IMG_PATH + mUser.getId() + image_type;
						img = img + mUser.getId() + image_type;
						base64 = Base64Util.byteToBase64(buff);
						mUser.setImg(base64);
						break;
					}

					FileUtil.writeFile(filePath, buff);
				}
			}
		} catch (Exception e) {
			jr.setCode(Constant.FAIL);
			jr.setMsg("Not select image");
			return jr;
		}
		mUser.setIdcard(server_path + idcard);
		mUser.setImg(server_path + img);
		mService.sendToMQ(mUser);
		MUser newUser = mService.update(mUser);
		session.setAttribute("m", newUser);
		jr.setCode(Constant.SUCCESS);
		jr.setData(newUser);
		return jr;
	}

	@RequestMapping(value = "muser/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) throws UnknownHostException {

		session.removeAttribute("m");
		return "redirect:/login.jsp";

	}

	@ResponseBody
	@RequestMapping("sec/muser/update/state")
	public JsonResult updateAndSet(String mid, int state, int block,HttpSession session) {
		
		JsonResult result = new JsonResult();
		MUser m = null;

		try {
			m = mService.updateInfo(mid, block, state);
		} catch (Exception e) {
			result.setCode(Constant.FAIL);
		}
		if (m != null) {
			session.setAttribute("m", m);
			result.setCode(Constant.SUCCESS);
		} else {
			result.setCode(Constant.FAIL);
		}
		return result;
	}

}
